package com.servlet;

import com.dao.CardDao;
import com.dao.CardtypeDao;
import com.dao.Impl.*;
import com.dao.OrderDao;
import com.dao.OrderinfoDao;
import com.entity.*;
import com.util.MyUtil;
import com.util.TransBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 沐白
 */
@WebServlet(value = "/commodityController/*")
public class CommodityConServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methon = MyUtil.getMethon(request);
        switch (methon) {
            case "show":
                select(request, response);
                break;
            case "showhy":
                selecthy(request, response);
                break;
            case "findByhyId":
                findByhyId(request, response);
                break;
            case "findByDdId":
                findByDdId(request, response);
                break;
            case "addOrder":
                addOrder(request, response);
                break;
            case "disCount":
                disCount(request, response);
                break;
            default:
                break;
        }
    }

    private void disCount(HttpServletRequest request, HttpServletResponse response) {
        String cardtypeName = request.getParameter("cardtypeName");
        double coefficient = new CardtypeDaoImpl().findByCoefficient(cardtypeName);
        MyUtil.jsonWriter(response,coefficient);
    }

    /**
     *
     * @param request
     * @param response
     */
    private void addOrder(HttpServletRequest request, HttpServletResponse response) {
        OrderDao odao = new OrderDaoImpl();
        OrderinfoDao oinfodao = new OrderinfoDaoImpl();
        CardtypeDao ctypedao = new CardtypeDaoImpl();
        CardDao cdao = new CardDaoImpl();
        GoodsDaoImpl goodsDao = new GoodsDaoImpl();

        Map<String, String[]> map = request.getParameterMap();
        Order order = new Order();
        TransBean.populate(order,map);
        order.setCredit((int) order.getPrice());
        Card card=null;
        if(order.getCardId()!=null&&!order.getCardId().equals("")){
            card = cdao.findById(order.getCardId());
            if(card.getAmount()<order.getPrice()){
                MyUtil.jsonWriter(response,"2");
                return;
            }
            Cardtype cardtype = ctypedao.findByLevelId(card.getLevelId());
            order.setCardType(cardtype.getLevel());
            Double d = order.getPrice()*cardtype.getCoefficient();
            order.setPay(new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }else{
            order.setPay(order.getPrice());
        }

        List<Orderinfo> oinfos=null;
        if(map.get("goodsId[]")!=null){
            oinfos = new ArrayList<>();
            for (int i = 0; i < map.get("goodsId[]").length; i++) {
                Orderinfo oinfo = new Orderinfo();
                oinfo.setOrderId(order.getOrderId());
                oinfo.setGoodsId(Integer.valueOf(map.get("goodsId[]")[i]));
                oinfo.setGoodsNumber(Integer.valueOf(map.get("goodsNum[]")[i]));
                oinfo.setGoodsPrice(Double.valueOf(map.get("goodsPrice[]")[i]));
                oinfo.setGoodsCredit((int) oinfo.getGoodsPrice());
                goodsDao.updateByNameCountjian(oinfo.getGoodsId(),oinfo.getGoodsNumber());
                goodsDao.updateNumstatus(Integer.valueOf(map.get("goodsId[]")[i]));
                oinfos.add(oinfo);
            }
        }
        if(oinfos!=null){
            for (Orderinfo oinfo : oinfos) {
                oinfodao.add(oinfo);
            }
        }
        int oint = odao.insertOrder(order);
        if(card!=null){
            cdao.updateAmount(card.getCardId(),card.getAmount()-order.getPay(),order.getCredit());
        }
        if(oint>0){
            if(card!=null){
                MyUtil.jsonWriter(response,card.getCardId());
            }else{
                MyUtil.jsonWriter(response,"1");
            }
        }else{
            MyUtil.jsonWriter(response,"0");
        }
    }

    /**
     *
     * @param request
     * @param response
     */
    private void findByDdId(HttpServletRequest request, HttpServletResponse response) {
        MyUtil.jsonWriter(response,new OrderDaoImpl().findByIdAuto()+1);
    }

    /**
     * @param request
     * @param response
     */
    private void findByhyId(HttpServletRequest request, HttpServletResponse response) {
        Integer cardId = Integer.valueOf(request.getParameter("cardId"));
        Card card = new CardDaoImpl().findById(cardId);
        if (card != null) {
            User user = null;
            if (card.getUserId() != null) {
                user = new UserDaoImpl().finduserId(card.getUserId());
            }
            if (user != null) {
                card.setUser(user);
            }
            card.setCardtype(new CardtypeDaoImpl().findByLevelId(card.getLevelId()));
        }
        MyUtil.jsonWriter(response, card);
    }

    /**
     * @param request
     * @param response
     * @return
     */
    private void select(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String[]> maps = request.getParameterMap();
        PageBean<Goods> page = new PageBean();
        TransBean.populate(page, maps);
        new GoodsDaoImpl().findAllStatus(page);
        page.setStartIndex();
        List<Goods> goods = page.getData();
        if (goods != null) {
            for (int i = 0; i < goods.size(); i++) {
                Goods good = goods.get(i);
                good.setUnit(new UnitDaoImpl().findById(good.getUnitId()));
                good.setCategory(new CateGoryDaoImp().findById(good.getCategoryId()));
            }
        }
        page.setData(goods);
        MyUtil.jsonWriter(response, page);
    }

    /**
     * @param request
     * @param response
     */
    private void selecthy(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String[]> maps = request.getParameterMap();
        PageBean<Card> page = new PageBean();
        TransBean.populate(page, maps);
        new CardDaoImpl().findAllPage(page);
        page.setStartIndex();
        List<Card> cards = page.getData();
        if (cards != null) {
            for (int i = 0; i < cards.size(); i++) {
                Card card = cards.get(i);
                User user = null;
                if (card.getUserId() != null) {
                    user = new UserDaoImpl().finduserId(card.getUserId());
                }
                if (user != null) {
                    card.setUser(user);
                }
                card.setCardtype(new CardtypeDaoImpl().findByLevelId(card.getLevelId()));
            }
        }
        MyUtil.jsonWriter(response, page);
    }

}
